package com.szrt.socket.ch04.url.demo01;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import org.junit.Test;

public class T5 {
	
	@Test
	public void url() throws Exception {
		URL url=new URL("http://127.0.0.1:8080/examples/HelloWorld.txt?phone=13926583118");
		//protocol协议
		
		url.getProtocol();

		//获得主机名称
		url.getHost();
		//端口号
		url.getPort();
		url.getPath();
		url.getFile();
		
		//获得相对路径
		url.getRef();
		//获得查询名
		url.getQuery();
		
		//读取服务端的资源
		InputStream is = url.openStream();
		byte[] b=new byte[2];
		int len;
		while((len=is.read(b))!=-1){
			String str=new String (b,0,len);
			System.out.println(str);
			
		}
		is.close();
		
		
		//读到url内容并且写入到一个文件中
		URLConnection con = url.openConnection();
		InputStream is2 = con.getInputStream();
		FileOutputStream fos=new FileOutputStream(new File("abc.txt"));
		byte[] b2=new byte[2];
		int len2;
		while((len2=is2.read(b2))!=-1){
			fos.write(b2, 0, len2);
		}
		fos.close();
		is2.close();
		
	}

}
